//
//  CNM_ExTimer.swift
//  CNMTools
//
//  Created by MrHong on 2023/11/10.
//

import UIKit

/**
 
 if #available(iOS 10.0, *) {
   // iOS 10之后采用`Block`方式解决Timer 循环引用问题
     timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] (timer) in
         guard let `self` = self else { return }
         ... do somthing
   })
 } else {
   // iOS 10之前的解决方案： 模仿系统的`closure` 解决Timer循环引用问题
     timer = Timer.cnm_ScheduledTimer(timeInterval: 1, repeats: true, closure: { [weak self] (timer) in
         guard let `self` = self else { return }
        ... do somthing
   })
 }
 */

// MARK: - 定时器，防止循环引用
public extension Timer {
    static func cnm_ScheduledTimer(timeInterval ti: TimeInterval, repeats yesOrNo: Bool, closure: @escaping (Timer) -> Void) -> Timer {
        return scheduledTimer(timeInterval: ti, target: self, selector: #selector(cnm_timerHandle(timer:)), userInfo: closure, repeats: yesOrNo)
    }
}

private extension Timer {
    @objc func cnm_timerHandle(timer: Timer) {
        var handleClosure = {}
        handleClosure = timer.userInfo as! () -> Void
        handleClosure()
    }
}
